#include "RingQueue.hpp"
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include "Task.hpp"

int myadd(int x,int y)
{
    return x + y;
}

void* consumer(void* args)
{
    RingQueue<Task> *rq = (RingQueue<Task>*)args;
    while(true)
    {
        // sleep(1);
        // int x;
        Task t;
        //1.从环形队列中获取任务与数据
        rq->pop(&t);
        //2.进行一定的处理 -- 不要忽略它的时间消耗问题
        // std::cout<< "消费：" << x << " : " << pthread_self() << std::endl;
        std::cout << "消费: " << pthread_self() << " x " << " + " << " y " << " = " <<  t() << std::endl;

    }

}

void* productor(void* args)
{
    RingQueue<Task> *rq = (RingQueue<Task>*)args;
    while(true)
    {

        //1.构建数据和任务对象 -- 一般是可以从外部来，不要忽略它的时间消耗问题
        int x = rand() % 100 + 1;
        usleep(rand()% 1000);
        int y = rand() % 100 + 1;
        Task t(x,y,myadd);
        // std::cout << "生产: " << x << " : " << pthread_self() << std::endl;
        std::cout << "生产: " << pthread_self() << " x " << " + " << " y " << " = ?" <<  std::endl;

        //2.推送到环形队列中去
        rq->push(t);//完成生产的过程
        // sleep(1);
    }
}

int main()
{
    srand((u_int64_t)time(nullptr) ^ getpid());
    pthread_t c[3],p[2];
    RingQueue<Task> *rq = new RingQueue<Task>();

    pthread_create(c,nullptr,consumer,(void*)rq);
    pthread_create(c+1,nullptr,consumer,(void*)rq);
    pthread_create(c+2,nullptr,consumer,(void*)rq);
    pthread_create(p,nullptr,consumer,(void*)rq);
    pthread_create(p+1,nullptr,productor,(void*)rq);

    pthread_join(c[0],nullptr);
    pthread_join(c[1],nullptr);
    pthread_join(c[2],nullptr);
    pthread_join(p[0],nullptr);
    pthread_join(p[1],nullptr);
    return 0;   
}